const express = require('express');
const router = express.Router();
const QQMapWX = require('../../api/js/qqmap-wx-jssdk'); // 修改：将腾讯地图 SDK 引入路径调整为 @/api/js/qqmap-wx-jssdk

// 初始化腾讯地图 SDK
const qqmapsdk = new QQMapWX({
    key: 'FAABZ-WBWRJ-LUJDS-WVK5L-KMBW3-YYFSQ' // 替换为实际的腾讯地图 API Key
});

/**
 * 获取用户当前位置并更新地址信息
 */
router.get('/updateLocation', (req, res) => {
    const { latitude, longitude } = req.query; // 修改：从 req.query 获取参数

    if (!latitude || !longitude) {
        return res.status(400).json({
            success: false,
            msg: '缺少经纬度参数'
        });
    }

    // 使用腾讯地图 SDK 进行逆地址解析
    qqmapsdk.reverseGeocoder({
        location: {
            latitude: parseFloat(latitude),
            longitude: parseFloat(longitude)
        },
        success(result) {
            const addressInfo = {
                city: result.result.address_component.city,
                district: result.result.address_component.district,
                street: result.result.address_component.street,
                province: result.result.address_component.province,
                address: result.result.address,
                name: result.result.ad_info.name,
                city_code: result.result.ad_info.city_code,
                lat: result.result.location.lat,
                lng: result.result.location.lng
            };

            return res.json({
                success: true,
                msg: '位置更新成功',
                data: addressInfo
            });
        },
        fail(error) {
            console.error('腾讯地图逆地址解析失败:', error);
            return res.status(500).json({
                success: false,
                msg: '位置更新失败',
                error: error.message
            });
        }
    });
});

module.exports = router;